﻿using Newtonsoft.Json;

namespace Qzb.MicroService.Common.HttpClientExtensions
{
    public class HttpRequest : IHttpRequest
    {
        public string Get(string url)
        {
            return Send(url, new()
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(url)
            });
        }

        public T? Get<T>(string url)
        {
            return Send<T>(url, new()
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(url)
            });
        }

        public T? Send<T>(string url, HttpRequestMessage message)
        {
            var html = Send(url, message);
            if (string.IsNullOrEmpty(html))
                return default;

            return JsonConvert.DeserializeObject<T>(html);
        }

        public string Send(string url, HttpRequestMessage message)
        {
            using HttpClient httpClient = new();
            var result = httpClient.SendAsync(message).Result;
            return result.Content.ReadAsStringAsync().Result;
        }
    }
}
